// lib/src/services/logging_service.dart
import 'dart:io';
import 'package:intl/intl.dart';

enum LogLevel { info, warning, error, debug }

class LoggingService {
  final String _logFilePath;
  final bool _logToConsole;

  LoggingService({String logFilePath = 'app.log', bool logToConsole = false})
    : _logFilePath = logFilePath,
      _logToConsole = logToConsole {
    // 可选：在服务初始化时创建日志文件（如果不存在）
    final file = File(_logFilePath);
    if (!file.existsSync()) {
      try {
        file.createSync(recursive: true);
        _log(
          LogLevel.info,
          'Log file created: $_logFilePath',
          isInternal: true,
        );
      } catch (e) {
        print('Failed to create log file: $e'); // 如果日志服务本身失败，打印到控制台
      }
    }
  }

  void _log(LogLevel level, String message, {bool isInternal = false}) {
    final timestamp = DateFormat(
      'yyyy-MM-dd HH:mm:ss.SSS',
    ).format(DateTime.now());
    final logEntry =
        '[$timestamp] [${level.toString().split('.').last.toUpperCase()}] $message\n';

    try {
      final file = File(_logFilePath);
      file.writeAsStringSync(logEntry, mode: FileMode.append, flush: true);
      if (_logToConsole && !isInternal) {
        // 避免内部日志消息重复打印到控制台
        print(logEntry.trim());
      }
    } catch (e) {
      // 如果写入日志失败，则打印到控制台以确保消息不会丢失
      print('Failed to write to log file: $e');
      print('Original log message: $logEntry');
    }
  }

  void info(String message) {
    _log(LogLevel.info, message);
  }

  void warning(String message) {
    _log(LogLevel.warning, message);
  }

  void error(String message, {Object? error, StackTrace? stackTrace}) {
    String fullMessage = message;
    if (error != null) {
      fullMessage += '\nError: $error';
    }
    if (stackTrace != null) {
      fullMessage += '\nStackTrace: $stackTrace';
    }
    _log(LogLevel.error, fullMessage);
  }

  void debug(String message) {
    _log(LogLevel.debug, message);
  }
}
